package com.bwf.ref;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * @Version v1.0
 * @Description: TODO
 * @Author ZHANZHONGXIN
 * @Date 2022/5/31 15:25
 * @Copyright 博为峰
 */
public class RefDemo02 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
//        m1();
//        m2();
        Class<?> aClass = Class.forName("com.bwf.ref.Student");
        Method method = aClass.getMethod("m1", String.class);

        Constructor<?> constructor = aClass.getConstructor(String.class, int.class);
        Student student = (Student) constructor.newInstance("张三", 20);

        method.invoke(student, "张三");

    }

    private static void m2() throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class<?> aClass = Class.forName("com.bwf.ref.Student");
        //获取所有公共的成员变量
        Field[] fields = aClass.getFields();
        //获取所有声明的成员变量
        fields = aClass.getDeclaredFields();
//        Arrays.stream(fields).forEach(System.out::println);
        Field name = aClass.getField("name");

        Constructor<?> constructor = aClass.getConstructor(String.class, int.class);
        Student student = (Student) constructor.newInstance("张三", 20);

        name.set(student, "李四");

        System.out.println(student.name);
    }

    private static void m1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class<?> aClass = Class.forName("com.bwf.ref.Student");
        //获取所有公共的构造方法
        Constructor<?>[] constructors = aClass.getConstructors();
        //获取所有声明的构造方法
        constructors = aClass.getDeclaredConstructors();
//        for (Constructor constructor : constructors) {
//            System.out.println("constructor = " + constructor);
//        }
        Stream<Constructor<?>> stream = Arrays.stream(constructors);
//        stream.forEach(constructor -> System.out.println("constructor = " + constructor));
//        stream.forEach(System.out::println);

        //获取指定的构造方法
        Constructor<?> constructor = aClass.getConstructor(String.class, int.class);
//        System.out.println("constructor = " + constructor);
        Student student = (Student) constructor.newInstance("张三", 20);
    }
}
